#include "storeCarInf.h"
#include "string.h"
#include "CANProcess.h"
#include "tim_hw.h"
#include "CarMonitor.h"
#include "fmc_flash.h"
#include "globalDef.h"

extern vehicle_state_updata tagCarS;

checkSaveCarInf_TypeDef 	tagCarInfSave = {0};


//保存结构体
uint32_t saveprintinfo_t(printinfo_t *pMsg)
{
	uint16_t len;
	
	len = sizeof(printinfo_t);
	
	return savePara1024WithAdr(FMC_PRI_INFO_ADR, (uint8_t*)(pMsg), len);
	
}
uint32_t getprintinfo_t(printinfo_t *pMsg)
{
	uint16_t len;
	
	len = sizeof(printinfo_t);
	
	return readPara1024WithAdr(FMC_PRI_INFO_ADR, (uint8_t*)(pMsg), len);
	
}
//点火时每小时存1次，熄火瞬间存一次，发现12V断电存1次
//1秒钟被调用1次
void regularCheckSaveCarInf(void)
{
	uint8_t needSave = 0;
	uint8_t carAccSta;
	
	//如果当前是断电状态，只存储1次
	if (getPowerOffSta() == 0x01)
	{
		if (tagCarInfSave.powerOffSta == 0x00)
		{
			tagCarInfSave.powerOffSta = 1;
			needSave = 1;
		}
	}
	else
	{
		tagCarInfSave.powerOffSta = 0;
		
		//获取点火状态
		carAccSta = 0;
		if ((u8AutoIgSt() & 0x08) == 0x08)
		{
			carAccSta = 1;
		}
		
		switch(tagCarInfSave.accOffSta)
		{
			case 0x00:	//先判断当前是点火状态
					if (carAccSta == 0x01)
					{
						tagCarInfSave.SecCntOld = get1sCounter();
						tagCarInfSave.accOffSta++;
					}
				break;
			case 0x01:
				if (carAccSta == 0x00)
				{
					needSave = 1;
					tagCarInfSave.accOffSta = 0;
				}
				else
				{
					if ((get1sCounter() - tagCarInfSave.SecCntOld) > 3600)
					{
						tagCarInfSave.SecCntOld = get1sCounter();
						needSave = 1;
					}
				}
				break;
			
			default:
				break;
		}
	}

	if (needSave == 0x01)
	{
		saveCarInf();
	}
}


//保存车身结构体
void saveCarInf(void)
{
#if( MCU_SAVE_DATA_ENABLE == 1 )
	uint16_t len;
	
	len = sizeof(vehicle_state_updata);
	
	if (len > 1000)
	{
		return;
	}
	
	savePara1024WithAdr(FMC_CARINF_ADR, (uint8_t*)(&tagCarS), len);
	savePara1024WithAdr(FMC_CARINF_ADR2, (uint8_t*)(&tagCarS), len);
#endif	
}

//取出历史车身数据，覆盖车身结构体
void getCarInf(void)
{
#if( MCU_SAVE_DATA_ENABLE == 1 )
	uint16_t len;
	uint8_t reDa;
	
	len = sizeof(vehicle_state_updata);
	
	if (len > 1000)
	{
		return;
	}
	reDa = readPara1024WithAdr(FMC_CARINF_ADR, (uint8_t*)(&tagCarS), len);
	if (reDa != 0)
	{
		reDa = readPara1024WithAdr(FMC_CARINF_ADR2, (uint8_t*)(&tagCarS), len);
	}
	//readPara1024((uint8_t*)(&tagCarS), len);
#endif
}

//清车身历史数据
void clearCarInf(void)
{
	erase_fmc_flash(FMC_CARINF_ADR ,1);
	erase_fmc_flash(FMC_CARINF_ADR2 ,1);
}











